package com.youdelu.road;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.youdelu.road.adapter.GridAdapter;
import com.youdelu.road.bean.Attr;
import com.youdelu.road.bean.FileDir;
import com.youdelu.road.utils.AppConfig;
import com.youdelu.road.utils.BroadcastManager;
import com.youdelu.road.utils.Util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileManagerActivity extends AppCompatActivity  implements View.OnClickListener{

    public static final String PARENT_ID = "parent_id";
    public static final String ACTION_TYPE = "action_type";

    public static final  String ACTION_SAVE_CATE = "action_save_cate";
    public static final String ACTION_SAVE_FILE = "action_save_file";

    private GridView gridView;
    private GridAdapter gridAdapter;
    private TextView title ;
    private TextView upload,tips ;
    private Context mContext;
    private DbUtils db ;

    private int action_type ;
    private boolean show_add_file = false ;
    private List<FileDir> data  = null;

    private FileDir parent = null,last=null;
    private Map<Integer,FileDir> map = new HashMap<>();

    private String action_name1 = "移动附件";
    private String action_name2 = "添加附件";
    private String action_name3 = "编辑附件";
    private String action_name = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_manager);
        mContext = this ;
        parent = new FileDir();
        parent.setId(0);
        parent.setParent_id(0);
        parent.setName("根");


        db= Util.db;

        title = findViewById(R.id.title);
        upload = findViewById(R.id.upload);
        tips = findViewById(R.id.tips);
        final Intent intent = getIntent();
        action_type = intent.getIntExtra(ACTION_TYPE,0);
        if(action_type==MainActivity.FILE_MOVE){
            title.setText(action_name1);
            upload.setVisibility(View.GONE);
            tips.setVisibility(View.VISIBLE);
            tips.setText("小提示:长按附件可拖动到地图");
            action_name = action_name1;
        }else  if(action_type ==MainActivity.FILE_ADD){
            title.setText(action_name2);
            show_add_file = true ;
            action_name = action_name2;
        }else if(action_type == MainActivity.FILE_SET){
            title.setText(action_name3);
            upload.setVisibility(View.GONE);
            tips.setVisibility(View.VISIBLE);
            tips.setText("小提示:长按类别或点击附件可编辑或删除");
            action_name = action_name3;
        }


        gridView = findViewById(R.id.list);
        gridAdapter = new GridAdapter(mContext,data,show_add_file);
        gridView.setAdapter(gridAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                FileDir fileDir =(FileDir) view.getTag(R.id.tag_first);
                if(fileDir.getType()==2){
                    Intent intent = new Intent();
                    intent.setClass(mContext,AddCateActivity.class);
                    intent.putExtra(PARENT_ID,parent.getId());
                    startActivity(intent);
                }else if(fileDir.getType()==0){
                    last = parent;
                    parent = fileDir;
                    map.put(fileDir.getId(),parent);
                    reload();
                }else if(fileDir.getType()==1){
                    if(action_type == MainActivity.FILE_SET){
                        Intent intent1 = new Intent();
                        intent1.putExtra("id",fileDir.getId());
                        intent1.putExtra("name",fileDir.getName());
                        intent1.putExtra("image",fileDir.getDir());
                        intent1.setClass(mContext,AddFileActivity.class);
                        startActivity(intent1);
                    }
                }
            }
        });
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                FileDir fileDir =(FileDir) view.getTag(R.id.tag_first);
                if(fileDir.getType()==0){
                    if(action_type == MainActivity.FILE_SET){
                        Intent intent1 = new Intent();
                        intent1.putExtra("id",fileDir.getId());
                        intent1.putExtra("name",fileDir.getName());
                        intent1.putExtra("image",fileDir.getDir());
                        intent1.setClass(mContext,AddCateActivity.class);
                        startActivity(intent1);
                    }
                }else if(fileDir.getType()==1){
                    /**
                     * 移动附件
                     */
                    if(action_type == MainActivity.FILE_MOVE){
                        Attr attr = new Attr();
                        attr.setPath(fileDir.getDir());
                        attr.setTitle(fileDir.getName());
                        attr.setTitleShow(false);
                        attr.setState(0);
                        attr.setPointX(0);
                        attr.setPointY(0);
                        attr.setId(-1);
                        BroadcastManager.getInstance(mContext).sendBroadcast(MainActivity.PUT_ATTR,attr);
                        finish();
                    }
                }
                return true;
            }
        });
        title.setOnClickListener(this);
        upload.setOnClickListener(this);
        initBordcast();
        reflushAdapter();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.title:
                if(last!=null){
                    int parent_id = last.getParent_id();
                    parent =  last;
                    if(parent_id>0) {
                        last = map.get(parent_id);
                    }else {
                        last.setId(0);
                        last.setParent_id(0);
                        last.setName("根");
                        map.clear();
                    }
                    reload();
                }
                break;
            case R.id.upload:
                Intent intent = new Intent();
                intent.setClass(mContext,AddFileActivity.class);
                startActivity(intent);
                break;
        }
    }

    public void reload(){
        if(parent.getId()>0){
            Drawable drawable = getResources().getDrawable(R.drawable.back);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            title.setCompoundDrawables(drawable, null, null, null);
            String n = "返回 "+last.getName()+"\\"+parent.getName()+"   "+action_name;
            title.setText(n);
            tips.setVisibility(View.GONE);
        }else {
            title.setCompoundDrawables(null, null, null, null);
            String n =  action_name;
            title.setText(n);
        }
        reflushAdapter();
    }

    public void reflushAdapter(){
        data = Util.findList(db,parent.getId());
        gridAdapter.update(data);
    }

    /**
     * 初始化广播
     */
    public void initBordcast(){
        /**
         *  接收保存分类的广播
         */
        BroadcastManager.getInstance(mContext).addAction(ACTION_SAVE_CATE, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String name = intent.getStringExtra("name");
                String path = intent.getStringExtra("path");
                int id = intent.getIntExtra("id",-1);
                FileDir fileDir = new FileDir();
                if(id!=-1){
                    fileDir.setId(id);
                }
                if(name.equals("-1#")){
                    Util.delete(db,fileDir);
                    Toast.makeText(mContext,"已删除",Toast.LENGTH_SHORT).show();
                }else{
                    fileDir.setParent_id(parent.getId());
                    fileDir.setName(name);
                    fileDir.setDir(path);
                    fileDir.setType(0);
                    Util.save(db,fileDir);
                }
                reflushAdapter();
            }
        });
        /**
         * 接收保存文件的广播
         */
        BroadcastManager.getInstance(mContext).addAction(ACTION_SAVE_FILE, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String name = intent.getStringExtra("name");
                String path = intent.getStringExtra("path");
                int id = intent.getIntExtra("id",-1);
                FileDir fileDir = new FileDir();
                if(id!=-1){
                    fileDir.setId(id);
                }
                if(name.equals("-1#")){
                    Util.delete(db,fileDir);
                    Toast.makeText(mContext,"已删除",Toast.LENGTH_SHORT).show();
                }else {
                    fileDir.setParent_id(parent.getId());
                    fileDir.setName(name);
                    fileDir.setDir(path);
                    fileDir.setType(1);
                    Util.save(db, fileDir);
                }
                reflushAdapter();
            }
        });

    }
    @Override
    protected void onDestroy() {
        BroadcastManager.getInstance(mContext).destroy(ACTION_SAVE_CATE);
        BroadcastManager.getInstance(mContext).destroy(ACTION_SAVE_FILE);
        super.onDestroy();
    }

}
